// 列表页逻辑代码
// 0. 获取元素
const cateBox = document.querySelector('.category > .right')
const filterBox = document.querySelector('.filter > .right')
const saleBox = document.querySelector('.sale > .right')
const sortBox = document.querySelector('.sort > .right')
const listBox = document.querySelector('.list')
const leftBtn = document.querySelector('.pagenation > .right > .left')
const rightBtn = document.querySelector('.pagenation > .right > .right')
const totalBtn = document.querySelector('.pagenation > .right > .total')
const selectBox = document.querySelector('.pagenation > .right > select')
const inp = document.querySelector('.pagenation > .right > input')
const box = document.querySelector('.box')
const searchInp = document.querySelector('.search > .right > input')

getCateList()
async function getCateList() {
  const res = await pAjax({ url: 'http://localhost:8888/goods/category', dataType: 'json' })

  let str = '<li class="cate active">全部</li>'
  res.list.forEach(item => {
    str += `
      <li class="cate">${ item }</li>
    `
  })
  cateBox.innerHTML = str
}

const listInfo = {
  current: 1,
  pagesize: 12,
  search: '',
  filter: '',
  saleType: 10,
  sortType: 'id',
  sortMethod: 'ASC',
  category: ''
}

getGoodsList()
async function getGoodsList() {
  const res = await pAjax({
    url: 'http://localhost:8888/goods/list',
    dataType: 'json',
    data: listInfo
  })

  let str = ''
  res.list.forEach(item => {
    str += `
      <li data-id="${ item.goods_id }">
        <div class="show">
          <img src="${ item.img_big_logo }" alt="">
          ${ item.is_hot ? '<span class="hot">HOT</span>' : '' }
          ${ item.is_sale ? '<span class="sale">SALE</span>' : '' }
        </div>
        <div class="info">
          <p class="title">
            ${ item.title }
          </p>
          <p class="price">
            <span class="current">
              ￥${ item.current_price }
            </span>
            <span class="old">
              ￥${ item.price }
            </span>
          </p>
          <p class="add">
            <button data-id="${ item.goods_id }">加入购物车</button>
          </p>
        </div>
      </li>
    `
  })
  listBox.innerHTML = str

  leftBtn.className = listInfo.current === 1 ? 'left disable' : 'left'
  rightBtn.classList = listInfo.current === res.total ? 'right disable' : 'right'
  totalBtn.innerText = listInfo.current + ' / ' + res.total
  selectBox.value = listInfo.pagesize
  inp.value = listInfo.current
  inp.dataset.total = res.total
}


box.addEventListener('click', e => {

  if (e.target.className === 'cate') {
    for (let i = 0; i < cateBox.children.length; i++) {
      cateBox.children[i].classList.remove('active')
    }
    e.target.classList.add('active')

    const text = e.target.innerText
    listInfo.category = text === '全部' ? '' : text
    listInfo.current = 1

    getGoodsList()
  }

  if (e.target.className === 'filter_item') {
    // 修改类名
    for (let i = 0; i < filterBox.children.length; i++) {
      filterBox.children[i].classList.remove('active')
    }
    e.target.classList.add('active')

    listInfo.filter = e.target.dataset.type
    listInfo.current = 1

    getGoodsList()
  }

  if (e.target.className === 'sale_item') {
    for (let i = 0; i < saleBox.children.length; i++) {
      saleBox.children[i].classList.remove('active')
    }
    e.target.classList.add('active')

    listInfo.saleType = e.target.dataset.type
    listInfo.current = 1

    getGoodsList()
  }

  if (e.target.className === 'sort_item') {
    for (let i = 0; i < sortBox.children.length; i++) {
      sortBox.children[i].classList.remove('active')
    }
    e.target.classList.add('active')

    listInfo.sortType = e.target.dataset.type
    listInfo.sortMethod = e.target.dataset.method

    getGoodsList()
  }

  if (e.target.className === 'right' && e.target.nodeName === 'SPAN') {
    listInfo.current++
    getGoodsList()
  }

  if (e.target.className === 'left' && e.target.nodeName === 'SPAN') {
    listInfo.current--
    getGoodsList()
  }

  if (e.target.className === 'go') {
    let page = e.target.previousElementSibling.value - 0
    const total = e.target.previousElementSibling.dataset.total - 0

    if (!page) page = 1
    if (page < 1) page = 1
    if (page >= total) page = total
    page = parseInt(page)

    listInfo.current = page

    getGoodsList()
  }
})

selectBox.addEventListener('change', () => {
  listInfo.pagesize = selectBox.value - 0
  listInfo.current = 1
  getGoodsList()
})

searchInp.addEventListener('input', () => {
  listInfo.search = searchInp.value.trim()
  listInfo.current = 1
  getGoodsList()
})

listBox.addEventListener('click', e => {
  // 注意: 让 li 内的标签都进行穿透效果
  if (e.target.nodeName === 'LI') {
    const goodsId = e.target.dataset.id
    window.sessionStorage.setItem('goodsId', goodsId)
    console.log(goodsId)

    window.location.href = './detail.html'
  }

  if (e.target.nodeName === 'BUTTON') {
    const goodsId = e.target.dataset.id
    addCart(goodsId)
  }
})

// 加入购物车
async function addCart(goodsId) {
  const id = window.localStorage.getItem('id')
  const token = window.localStorage.getItem('token')

  if (!id) {
    const res = window.confirm('您还没有登录, 请登录后在购买, 点击确定跳转回登录页, 点击取消留在当前页面')
    if (res) {
      window.location.href = './login.html'
      return
    }
    return
  }

  const res = await pAjax({
    url: 'http://localhost:8888/cart/add',
    method: 'POST',
    data: { id, goodsId },
    headers: { authorization: token },
    dataType: 'json'
  })

  if (res.code === 401) {
    const res = window.confirm('您的登录已经过期, 请重新登录后在购买, 点击确定跳转回登录页, 点击取消留在当前页面')
    if (res) {
      window.location.href = './login.html'
      return
    }
    return
  }

  if (res.code === 1) {
    alert('加入购物车成功')
  }
}



// 
const id = window.localStorage.getItem('id')
const token = window.localStorage.getItem('token')

const onBox = document.querySelector('.on')
const offBox = document.querySelector('.user_name')
console.log(onBox)
console.log(offBox)
if (!id) {
  onBox.classList.remove('active')
  offBox.classList.add('active')
}

const xhr = new XMLHttpRequest()

xhr.open('GET', 'http://localhost:8888/users/info?id=' + id)

xhr.onload = function () {
  const res = JSON.parse(xhr.responseText)
  if (res.code === 401) {
    onBox.classList.remove('active')
    offBox.classList.add('active')
  }

  if (res.code === 1) {
    onBox.firstElementChild.innerText = res.info.nickname
    offBox.classList.remove('active')
    onBox.classList.add('active')
  }
}

xhr.setRequestHeader('authorization', token)

xhr.send()

const logoutBtn = document.querySelector('.logout')
logoutBtn.addEventListener('click', async () => {
  const res = await pAjax({
    url: 'http://localhost:8888/users/logout',
    data: { id },
    dataType: 'json'
  })

  if (res.code === 1) {
    window.localStorage.removeItem('id')
    window.localStorage.removeItem('token')

    window.location.reload()
  }
})